package com.scujj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scujj.pojo.*;
import com.scujj.service.BlogService;
import com.scujj.service.CommentService;
import com.scujj.service.ThumbsUpService;
import com.scujj.service.UserService;
import com.scujj.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    UserService userService;

    @Autowired
    BlogService blogService;

    @Autowired
    ThumbsUpService thumbsUpService;

    @Autowired
    CommentService commentService;

    @GetMapping("/thumb_up")
    Result thumbUp(@RequestParam(value = "bid",defaultValue = "0") long bid, @RequestHeader HashMap<String,String> header){
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        Blog blog = blogService.getBlogById(bid);
        if(blog==null){
            return Result.error("帖子不存在");
        }
        QueryWrapper<BlogThumbsUpNum> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",user.getId());
        wrapper.eq("bid",bid);
        BlogThumbsUpNum b= thumbsUpService.getOne(wrapper);

        if(b==null){
            thumbsUpService.save(new BlogThumbsUpNum().setUid(user.getId()).setBid(bid));
            blog.setThumbsUpNum(blog.getThumbsUpNum()+1);
            blogService.updateById(blog);
            return Result.success("点赞成功");
        } else {
            thumbsUpService.remove(wrapper);
            blog.setThumbsUpNum(blog.getThumbsUpNum()-1);
            blogService.updateById(blog);
            return Result.success("取消点赞成功");
        }
    }

    @GetMapping("/publish")
    Result commentBlog(@RequestParam(value = "bid") long bid, @RequestParam(value = "context") String context, @RequestHeader HashMap<String,String> header){
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        CommentBlog comment=new CommentBlog();
        comment.setUid(user.getId());
        comment.setBid(bid);
        comment.setContext(context);
        comment.setPublishTime(new Date());
        commentService.save(comment);
        return Result.success("评论成功",user.setPassword(null).setMoney(null));
    }
}
